package com.distribution.system.service.impl;

import cn.hutool.core.util.PhoneUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayFundTransUniTransferModel;
import com.alipay.api.domain.Participant;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.distribution.common.core.domain.entity.SysUser;
import com.distribution.common.exception.ServiceException;
import com.distribution.common.utils.DictUtils;
import com.distribution.common.utils.StringUtils;
import com.distribution.system.domain.dto.*;
import com.distribution.system.domain.entity.CmccDaCommissionReflection;
import com.distribution.system.domain.entity.FuluUploadPeople;
import com.distribution.system.domain.req.ReqResult;
import com.distribution.system.mapper.CmccDaCommissionReflectionMapper;
import com.distribution.system.mapper.SysUserMapper;
import com.distribution.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static com.distribution.common.utils.SecurityUtils.getUserId;
import static com.distribution.common.utils.SecurityUtils.getUsername;

/**
 * (CmccDaCommissionReflection)表服务实现类
 */
@Service("cmccDaCommissionReflectionService")
@Slf4j
public class CmccDaCommissionReflectionServiceImpl extends ServiceImpl<CmccDaCommissionReflectionMapper, CmccDaCommissionReflection> implements CmccDaCommissionReflectionService {
    private static final Logger agentWithdrawLog = LoggerFactory.getLogger("agentWithdrawLog");

    @Resource
    SysUserMapper sysUserMapper;
    @Value("${alipay.pay.privateKey}")
    private  String privateKey;
    @Value("${alipay.pay.appId}")
    private  String appId;
    @Value("${alipay.pay.certPath}")
    private  String certPath;
    @Value("${alipay.pay.alipayPublicCertPath}")
    private  String alipayPublicCertPath;
    @Value("${alipay.pay.rootCertPath}")
    private  String rootCertPath;

    @Resource
    FuluUploadPeopleService fuluUploadPeopleService;
    @Resource
    CmccDaAccountDetailService cmccDaAccountDetailService;
    @Resource
    AliSmsSendService aliSmsSendService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ReqResult addCmccDaCommissionReflection(CommissionReflectionDto commissionReflectionDto) {
        // 校验验证码
        /*ReqResult verifyReqResult = aliSmsSendService.verifySmsCode(commissionReflectionDto.getSmsCode(), commissionReflectionDto.getReflectionAccount());
        if (verifyReqResult.getCode() != 200) return verifyReqResult;*/
        // 获取用户信息
        Long userId = getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        agentWithdrawLog.info("用户【{}】提现账户【{}】申请提现【{}】元", sysUser.getUserId(),
                commissionReflectionDto.getReflectionAccount(), commissionReflectionDto.getReflectionAmount());
        // 设置信息
        CmccDaCommissionReflection commissionReflection = new CmccDaCommissionReflection();
        commissionReflection.setReflectionAccount(commissionReflectionDto.getReflectionAccount());
        commissionReflection.setReflectionAccountName(commissionReflectionDto.getReflectionAccountName());
        commissionReflection.setReflectionAmount(commissionReflectionDto.getReflectionAmount());
        commissionReflection.setCreateUserId(userId.intValue());
        commissionReflection.setCreateUserName(sysUser.getNickName());
        commissionReflection.setCreateAccount(sysUser.getUserName());
        commissionReflection.setCreateTime(new Date());
        commissionReflection.setUpdateTime(new Date());
        commissionReflection.setReflectionType(commissionReflectionDto.getReflectionType());
        String reflectionTypeDesc = DictUtils.getDictLabel("sys_reflection_type", String.valueOf(commissionReflectionDto.getReflectionType()));
        if (StringUtils.isEmpty(reflectionTypeDesc)) {
            agentWithdrawLog.info("提现方式【{}】不能使用,请选择平台提现方式!", reflectionTypeDesc);
            throw new ServiceException("该提现方式不能使用,请选择平台提现方式!");
        }
        commissionReflection.setReflectionTypeDesc(reflectionTypeDesc);
//        if (commissionReflectionDto.getReflectionType() == 1) {
//            commissionReflectionDto.setGrantType("支付宝");
//        }
        commissionReflection.setReflectionState(1);
        commissionReflection.setReflectionStateDesc("审核中");
        if (sysUser.getCommission().compareTo(BigDecimal.ZERO) <= 0) {
            agentWithdrawLog.info("账户余额【{}】小于0，无法提现!!", sysUser.getCommission());
            throw new ServiceException("账户余额小于0，无法提现!");
        }
        if (commissionReflectionDto.getReflectionAmount().compareTo(sysUser.getCommission()) > 0) {
            agentWithdrawLog.info("提现金额【{}】不能大于账户余额【{}】", commissionReflectionDto.getReflectionAmount(), sysUser.getCommission());
            throw new ServiceException("提现金额不能大于账户余额!");
        }
        FuluUploadPeople fuluUploadPeople = fuluUploadPeopleService.lambdaQuery().eq(FuluUploadPeople::getUserId, userId).eq(FuluUploadPeople::getDeleteFlag, 0).one();
        if (fuluUploadPeople == null || !"3".equals(String.valueOf(fuluUploadPeople.getSignStatus()))) {
            agentWithdrawLog.info("没有认证或认证中，请先前往手机端或PC端资金管理认证!");
            throw new ServiceException("没有认证或认证中，请先前往手机端或PC端资金管理认证!");
        }
        // 提现类型是平台
        if (commissionReflectionDto.getReflectionType() == 2) {
            commissionReflection.setReflectionType(1);
            commissionReflection.setReflectionTypeDesc("支付宝");
            commissionReflection.setReflectionAccountName(fuluUploadPeople.getUserName());
            commissionReflection.setGrantType("支付宝");
            commissionReflection.setAccountType("支付宝账号");
            save(commissionReflection);
            // 减掉佣金
            sysUser.setUpdateTime(new Date());
            sysUser.setCommission(sysUser.getCommission().subtract(commissionReflectionDto.getReflectionAmount()));
            sysUserMapper.updateUser(sysUser);
            // 提现金额小于500
            if (commissionReflectionDto.getReflectionAmount().compareTo(new BigDecimal(500)) < 0) {
                try {
                    ProcessCommissionReflectionDTO processCommissionReflectionDTO = new ProcessCommissionReflectionDTO();
                    processCommissionReflectionDTO.setId(commissionReflection.getId());
                    processCommissionReflectionDTO.setReflectionState(1);
                    return processCmccDaCommissionReflection(processCommissionReflectionDTO);
                } catch (Exception e) {
                    agentWithdrawLog.info("提现打款异常：{}", e.getMessage());
                    throw new ServiceException("提现打款异常：" + e.getMessage());
                }
            } else {
                return ReqResult.success();
            }
        } else {
            agentWithdrawLog.info("当前仅支持平台提现!");
//            throw new ServiceException("当前仅支持平台提现!");
            return ReqResult.error("当前仅支持平台提现!");
        }


        /*else if (commissionReflectionDto.getReflectionType() == 2){
            commissionReflectionDto.setReflectionAccountName(fuluUploadPeople.getUserName());
            sysUser.setUpdateTime(new Date());
            sysUser.setCommission(sysUser.getCommission().subtract(commissionReflectionDto.getReflectionAmount()));
            sysUserMapper.updateUser(sysUser);
            save(commissionReflectionDto);
            FuluUploadPlan fuluUploadPlan = new FuluUploadPlan();
            fuluUploadPlan.setUserId(userId);
            if ("微信支付".equals(commissionReflectionDto.getGrantType())) {
                String openId = sysUser.getOpenId();
                if (StringUtils.isEmpty(openId)) {
                    throw new ServiceException("账号未绑定微信支付，无法使用微信提现。");
                }
                fuluUploadPlan.setAccountNumber(openId);
            } else {
                fuluUploadPlan.setAccountNumber(commissionReflectionDto.getReflectionAccount());
            }
            fuluUploadPlan.setAfterTaxAmount(commissionReflectionDto.getReflectionAmount());
            fuluUploadPlan.setGrantType(commissionReflectionDto.getGrantType());
            fuluUploadPlan.setIdCard(fuluUploadPeople.getIdCard());
            fuluUploadPlan.setMobile(fuluUploadPeople.getMobile());
            //XXX年XX月XX日-XXX年XX月XX日，完成了XXX任务，结算佣金为XXX元
            Date beginDayOfMonth = DateUtil.getBeginDayOfMonth();
            fuluUploadPlan.setRemark(formatter.format(beginDayOfMonth) + "-" + formatter.format(new Date()) + "完成卡号订单任务,结算金额为" + commissionReflectionDto.getReflectionAmount() + "元");
            fuluUploadPlan.setUserName(fuluUploadPeople.getUserName());
            commissionReflectionDto.setReflectionAccountName(fuluUploadPeople.getUserName());
            fuluUploadPlanService.uploadPlan(fuluUploadPlan);
            commissionReflectionDto.setOutBizNo(fuluUploadPlan.getOutBizNo());
            sysUser.setUpdateTime(new Date());
            sysUser.setCommission(sysUser.getCommission().subtract(commissionReflectionDto.getReflectionAmount()));
            sysUserMapper.updateUser(sysUser);
        }*/
    }

    /**
    * @Author: GodLu
    * @Date: 2025/1/20 13:56
    * @Description: 发送提现验证码
    * @param commissionReflectionDto 发送验证码Dto
    * @return: ReqResult
    */
    @Override
    public ReqResult sendCommissionReflectionSmsCode(CommissionReflectionDto commissionReflectionDto) {
        // 获取用户信息
        Long userId = getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        String phoneNumber = sysUser.getPhoneNumber();
        if (StringUtils.isBlank(phoneNumber)){
            return ReqResult.error("当前账号未设置联系电话，请设置联系电话后提现");
        }
        if (!PhoneUtil.isMobile(phoneNumber)){
            return ReqResult.error("当前账号联系电话格式错误");
        }
        ReqResult reqResult = aliSmsSendService.genAndSendAliSmsCode(phoneNumber, commissionReflectionDto.getReflectionAccount());
        if (reqResult.getCode() != 200) return reqResult;
        return ReqResult.success("验证码已发送至您的联系电话" + phoneNumber + "，请注意查收");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
    public ReqResult processCmccDaCommissionReflection(ProcessCommissionReflectionDTO processCommissionReflectionDTO) {
        CmccDaCommissionReflection cmccDaCommissionReflection = getById(processCommissionReflectionDTO.getId());
        if (cmccDaCommissionReflection.getReflectionState() != 1) {
            throw new ServiceException("当前不在审核阶段，无需审核!");
        }
        SysUser sysUser = sysUserMapper.selectUserById(cmccDaCommissionReflection.getCreateUserId().longValue());
        sysUser.setUpdateTime(new Date());
        BeanUtils.copyProperties(processCommissionReflectionDTO,cmccDaCommissionReflection);
        BigDecimal reflectionAmount = cmccDaCommissionReflection.getReflectionAmount();// 提现金额
        if (processCommissionReflectionDTO.getReflectionState() == 2) {
            cmccDaCommissionReflection.setReflectionStateDesc("驳回");
            cmccDaCommissionReflection.setPayStatus(4);
            cmccDaCommissionReflection.setPayStatusDesc("打款失败");
            sysUser.setCommission(sysUser.getCommission().add(reflectionAmount));
            sysUserMapper.updateUser(sysUser);
        } else if (processCommissionReflectionDTO.getReflectionState() == 1) {
            cmccDaCommissionReflection.setReflectionState(3);
            cmccDaCommissionReflection.setReflectionStateDesc("审核通过");
            try {
                //调用支付宝
                CertAlipayRequest alipayConfig = new CertAlipayRequest();
                alipayConfig.setPrivateKey(privateKey);
                alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
                alipayConfig.setAppId(appId);
                alipayConfig.setCharset("UTF8");
                alipayConfig.setSignType("RSA2");
                alipayConfig.setEncryptor("");
                alipayConfig.setFormat("json");
                alipayConfig.setCertPath(certPath);
                alipayConfig.setAlipayPublicCertPath(alipayPublicCertPath);
                alipayConfig.setRootCertPath(rootCertPath);
                AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
                AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
                AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
                String id = UUID.randomUUID().toString();
                model.setOutBizNo(id);
                model.setRemark("单笔转账");
                model.setBusinessParams("{\"payer_show_name_use_alias\":\"true\"}");
                model.setBizScene("DIRECT_TRANSFER");
                Participant payeeInfo = new Participant();
                payeeInfo.setIdentity(cmccDaCommissionReflection.getReflectionAccount());
                payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
                payeeInfo.setName(cmccDaCommissionReflection.getReflectionAccountName());
                model.setPayeeInfo(payeeInfo);
                model.setTransAmount(reflectionAmount.toString());
                model.setProductCode("TRANS_ACCOUNT_NO_PWD");
                model.setOrderTitle("提现");
                request.setBizModel(model);
                log.info("调用支付宝入参:{}", JSONObject.toJSONString(request));
                AlipayFundTransUniTransferResponse response = alipayClient.certificateExecute(request);
                log.info("调用支付宝出参:{}", JSONObject.toJSONString(response));
                if (response.isSuccess()) {
                    cmccDaCommissionReflection.setPaymentDate(new Date());
                    cmccDaCommissionReflection.setPayStatus(3);
                    cmccDaCommissionReflection.setPayStatusDesc("打款成功");
                    // 添加资金明细
                    CmccDaAccountDetailAddDto cmccDaAccountDetailAddDto = new CmccDaAccountDetailAddDto();
                    cmccDaAccountDetailAddDto.setSysUser(sysUser);
                    cmccDaAccountDetailAddDto.setDetailType("2");
                    cmccDaAccountDetailAddDto.setFrontAmount(sysUser.getCommission().add(reflectionAmount));
                    cmccDaAccountDetailAddDto.setChangeAmount(reflectionAmount);
                    cmccDaAccountDetailAddDto.setAfterAmount(sysUser.getCommission());
                    cmccDaAccountDetailAddDto.setWithdrawId(cmccDaCommissionReflection.getId());
                    cmccDaAccountDetailService.addAccountDetail(cmccDaAccountDetailAddDto);
                } else {
//                    cmccDaCommissionReflection.setReflectionState(4);
//                    cmccDaCommissionReflection.setReflectionStateDesc("审核通过转账失败");
//                    sysUser.setCommission(sysUser.getCommission().add(cmccDaCommissionReflection.getReflectionAmount()));
//                    cmccDaCommissionReflection.setRemark(response.getSubMsg());
                    agentWithdrawLog.info("支付宝打款失败：{}", response.getSubMsg());
                    throw new ServiceException(response.getSubMsg());
                }
            } catch (AlipayApiException e) {
//                cmccDaCommissionReflection.setReflectionState(4);
//                cmccDaCommissionReflection.setReflectionStateDesc("审核通过转账失败");
//                sysUser.setCommission(sysUser.getCommission().add(cmccDaCommissionReflection.getReflectionAmount()));
//                cmccDaCommissionReflection.setRemark(e.getErrMsg());
                agentWithdrawLog.info("支付宝打款异常：{}", e.getErrMsg());
                throw new ServiceException(e.getErrMsg());
            }
        } else {
            agentWithdrawLog.info("系统跑神了,审核失败");
            throw new ServiceException("系统跑神了,审核失败");
        }
        cmccDaCommissionReflection.setProcessUserId(getUserId().intValue());
        cmccDaCommissionReflection.setProcessUserName(getUsername());
        cmccDaCommissionReflection.setUpdateTime(new Date());
        updateById(cmccDaCommissionReflection);
        return ReqResult.success();
    }

    @Override
    public List<CmccDaCommissionReflection> selectProcessCmccDaCommissionReflection(CmccDaCommissionReflectionDto cmccDaCommissionReflectionDto) {
        QueryWrapper<CmccDaCommissionReflection> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.orderByAsc("reflection_state");
        objectQueryWrapper.orderByDesc("create_time");
        if (StringUtils.isNotEmpty(cmccDaCommissionReflectionDto.getCreateUserName())) {
            objectQueryWrapper.eq("create_user_name", cmccDaCommissionReflectionDto.getCreateUserName());
        }
        if (StringUtils.isNotEmpty(cmccDaCommissionReflectionDto.getReflectionAccountName())) {
            objectQueryWrapper.eq("reflection_account_name", cmccDaCommissionReflectionDto.getReflectionAccountName());
        }
        if (cmccDaCommissionReflectionDto.getEndTime() != null) {
            objectQueryWrapper.le("create_time", cmccDaCommissionReflectionDto.getEndTime());
        }
        if (cmccDaCommissionReflectionDto.getBeginTime() != null) {
            objectQueryWrapper.ge("create_time", cmccDaCommissionReflectionDto.getBeginTime());
        }
        return list(objectQueryWrapper);
    }



}
